<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>仿淘宝侧边栏</title>
		<style type="text/css">
			* {
				margin: 0;
				padding: 0;
				box-sizing: border-box;
			}
			.w {
				width: 1200px;
				margin: 0 auto;
			}
			.marginTop_10 {
				margin-top: 10px;
			}
			.header {
				height: 100px;
				background-color: pink;
			}
			.banner {
				height: 200px;
				background-color: purple;
			}
			
			.focus {
				
				height: 1200px;
				background-color: mediumpurple;
			}
			.aside {
				position: absolute;
				top: 400px;
				left: 50%;
				margin-left: 601px;
				width: 50px;
				height: 150px;
				line-height: 150px;
				text-align: center;
				color: #fff;
				background-color: #684e4e;
			}
			.context {
				display: none;
			}
		</style>
	</head>
	<body>
		<div class="header w"></div>
		<div class="banner w marginTop_10"></div>
		<div class="focus w marginTop_10"></div>
		<div class="aside">
			<span class="context">返回顶部</span>
		</div>
		
		<script type="text/javascript">
			//获取对象
			var header = document.querySelector('.header');
			var banner = document.querySelector('.banner');
			var focus = document.querySelector('.focus');
			var aside = document.querySelector('.aside');
			var context = document.querySelector('.context');
			
			var bannerTop = banner.offsetTop;
			var focusTop = focus.offsetTop;
			var asideTop = aside.offsetTop - focusTop;
			//当滚动触发事件发生的时候
			document.addEventListener('scroll',function() {
				//当 header 头部被卷去的时候,侧边栏aside要变成固定定位
				if(window.pageYOffset > bannerTop) {
					aside.style.position = 'fixed';
					aside.style.top =  asideTop + 'px'
				} else {
					aside.style.position = 'absolute';
					aside.style.top = '400px'
				}
				
				//当focus部分被卷去的时候,显示文字
				if(window.pageYOffset > focusTop) {
					context.style.display = 'block';
				} else {
					context.style.display = 'none'
				}
			})
			
			//点击回到顶部事件
			context.addEventListener('click',function() {
				//因为滚动的是浏览器的窗口,所以对象是window
				animate(Window,0)
			})
			//定义动画函数
			function animate(obj,target,callback) {
				
				//计算缓冲的步长
				var step = (target - window.pageYOffset) / 15;
				//判断向上还是向下
				step = step > 0 ? Math.ceil(step) : Math.floor(step);
				//返回顶部的距离
				obj.timer = setInterval(function() {
					//如果卷去的部分等于目标距离就清除定时器
					if(window.pageYOffset == target) {
						clearInterval(obj.timer);
						callback && callback();
					}
					window.scroll(0,window.pageYOffset + step);
				},15)
				
			}
		</script>
	</body>
</html>
